package org.jboss.resteasy.springboot;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.util.ClassUtils;

public abstract class JaxrsApplicationScanner {
    private static final Logger logger = LoggerFactory.getLogger(JaxrsApplicationScanner.class);

    private static Map<String, Set<Class<? extends Application>>> packagesToClassesMap = new HashMap();

    public JaxrsApplicationScanner() {
    }

    public static Set<Class<? extends Application>> getApplications(List<String> packagesToBeScanned) {
        String packagesKey = createPackagesKey(packagesToBeScanned);
        if (!packagesToClassesMap.containsKey(packagesKey)) {
            packagesToClassesMap.put(packagesKey, findJaxrsApplicationClasses(packagesToBeScanned));
        }

        return (Set)packagesToClassesMap.get(packagesKey);
    }

    private static String createPackagesKey(List<String> packagesToBeScanned) {
        return String.join(",", packagesToBeScanned);
    }

    private static Set<Class<? extends Application>> findJaxrsApplicationClasses(List<String> packagesToBeScanned) {
        logger.info("Scanning classpath to find JAX-RS Application classes");
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AssignableTypeFilter(Application.class));
        Set<BeanDefinition> candidates = new HashSet();
        Iterator var4 = packagesToBeScanned.iterator();

        while(var4.hasNext()) {
            String packageToScan = (String)var4.next();
            Set<BeanDefinition> candidatesSubSet = scanner.findCandidateComponents(packageToScan);
            candidates.addAll(candidatesSubSet);
        }

        Set<Class<? extends Application>> classes = new HashSet();
        ClassLoader classLoader = JaxrsApplicationScanner.class.getClassLoader();
        Iterator var7 = candidates.iterator();

        Class<? extends Application> type;

        while(var7.hasNext()) {
            BeanDefinition candidate = (BeanDefinition)var7.next();

            try {
                type = (Class<? extends Application>) ClassUtils.forName(candidate.getBeanClassName(), classLoader);
                classes.add(type);
            } catch (ClassNotFoundException var10) {
                logger.error("JAX-RS Application subclass could not be loaded", var10);
            }
        }

        classes.remove(Application.class);
        return classes;
    }
}
